package net.lab1024.sa.admin.module.open.heartbeat;

import cn.hutool.extra.servlet.ServletUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.lab1024.sa.admin.constant.AdminSwaggerTagConst;
import net.lab1024.sa.admin.module.open.heartbeat.domain.DeviceHeartbeatReportForm;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@Tag(name = AdminSwaggerTagConst.Open.OPEN_HEARTBEAT)
public class DeviceHeartbeatController {

    private final DeviceHeartbeatService deviceHeartbeatService;

    public DeviceHeartbeatController(DeviceHeartbeatService deviceHeartbeatService) {
        this.deviceHeartbeatService = deviceHeartbeatService;
    }

    @NoNeedLogin
    @PostMapping("/heartbeat")
    public ResponseDTO<String> heartbeat(HttpServletRequest request,
                                         @Valid @RequestBody DeviceHeartbeatReportForm form) {
        String ip = ServletUtil.getClientIP(request);
        deviceHeartbeatService.putHeartbeatInQueue(form, ip);
        return ResponseDTO.ok("success");
    }

    @NoNeedLogin
    @GetMapping("/heartbeat/queue/size")
    public ResponseDTO<Integer> heartbeatCount() {
        Integer heartbeatCount = deviceHeartbeatService.getHeartbeatQueueSize();
        return ResponseDTO.ok(heartbeatCount);
    }
}
